/*
 * @Date: 2023-02-14 09:56:14
 * @LastEditTime: 2023-04-28 09:02:18
 */
import axios from 'axios';
import { useUserStore } from '@/store/index';
import { message } from 'ant-design-vue';
import router from '@/router';

const baseURL = 'http://string.api.huikaoedu.com';
const request = axios.create({
  baseURL: baseURL + '/',
  timeout: 60000,
  headers: {},
});

// 异常拦截处理器
const errorHandler = (error) => {
  return Promise.reject(error);
};

request.interceptors.request.use((config) => {
  const counter = useUserStore();
  config.headers.token = counter.token;
  return config;
}, errorHandler);

request.interceptors.response.use((response) => {
  // console.log(response);
  switch (response.data.code) {
    case 200:
      return response.data;
    case 2001:
      message.warning(response.data.msg, 2);
      router.push({ path: '/user/login' });
      break;
    case 2006:
      router.push('/');
      Modal.error({
        title: '警告',
        content: '您已在别的窗口打开，请留意...',
        onOk: () => {
          sessionStorage.clear();
        },
      });
      break;
    default:
      message.warning(response.data.msg, 2);
      return response.data.success;
  }
}, errorHandler);

export { request, baseURL };
